<?php

namespace App\Remote\Mybank;

use App\Kuafu\Mybank\Enum\MybankFunctionEnum;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Utils;
use Illuminate\Http\Request;

class MybankUploadRemote extends Remote
{
    /**
     * 预入驻
     *
     * @param string $filePath
     * @param string $photoType
     * @return mixed
     * @throws GuzzleException
     * @throws \App\Exceptions\BaseException
     */
    public static function uploadPhoto(string $filePath, string $photoType)
    {
        $orderNoGenerateFunc = function (string $prefix) {
            return vsprintf("%s%s%s", [
                $prefix,
                date("Ymd", time()),
                str_pad(
                    floor(microtime(true) * 1000) - strtotime(date('Y-m-d 00:00:00'), time()) * 1000,
                    8,
                    "0",
                    STR_PAD_LEFT
                )
            ]);
        };


        $body = [
            'IsvOrgId'   => self::getIsvOrgId(),
            'PhotoType'  => $photoType,
            // 图片类型。可选值：01 身份证正面,02 身份证反面,03 营业执照,04组织机构代码证,05 开户许可证,06 门头照,07 其他,08 收银台照片,09 门店内景照片
            'OutTradeNo' => $orderNoGenerateFunc("UP"),
            'Function'   => 'ant.mybank.merchantprod.merchant.uploadphoto',
            'Version'    => '1.0.0',
            'AppId'      => self::getAppid(),
            'ReqTime'    => date('YmdHis')
        ];

        ksort($body);
        openssl_sign(
            urlencode(http_build_query($body)),
            $signature,
            openssl_pkey_get_private(Remote::getPrivateKey()),
            OPENSSL_ALGO_SHA256
        );
        $sign              = base64_encode($signature);
        $body['Signature'] = $sign;

        return self::customRequestV2(
            config('pay.mybank.bkUploadServerUrl'),
            Request::METHOD_POST,
            [
                'multipart' => collect($body)->map(function ($v, $k) {
                    return [
                        'name'     => $k,
                        'contents' => $v
                    ];
                })->merge([
                    [
                        'name'     => 'Picture',
                        'contents' => Utils::tryFopen($filePath, 'r'),
                        'filename' => $filePath
                    ]
                ])->values()->toArray()
            ],
            ["Content-Type" => "multipart/form-data"]
        );
    }

}
